<template>
  <div class="page-add-or-update">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{ title }}
      </div>
    </div>

    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      class="form-box"
      label-width="auto"
      @submit.prevent
    >
      <!--套餐名称-->
      <el-form-item
        :label="$t('popupAd.popupName')"
        prop="popupName"
        required
      >
        <el-input
          v-model="dataForm.popupName"
          :disabled="readonly"
          show-word-limit
          maxlength="20"
          style="width: 355px"
          :placeholder="$t('popupAd.popupName')"
          @blur="dataForm.popupName=dataForm.popupName.trim()"
        />
      </el-form-item>
      <el-form-item
        :label="$t('popupAd.triggerPage')"
        prop="pageType"
        required
      >
        <!-- 1.平台首页 2.会员中心 3.支付成功 4.店铺首页 5.商品详情" -->
        <el-radio-group
          v-model="dataForm.pageType"
          :disabled="readonly"
        >
          <el-radio :label="4">
            {{ $t('popupAd.shopHome') }}
          </el-radio>
          <el-radio :label="5">
            {{ $t('popupAd.prodDetail') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        prop="jumpUrl"
        required
      >
        <template #label>
          <div class="custom-label">
            <span class="label">{{ $t('popupAd.redirect') }}</span>
            <el-tooltip placement="top">
              <template #content>
                {{ $t('popupAd.redirectTips') }}
              </template>
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        <div
          :class="['jumpurl-box',{disabled:readonly}]"
          @click="onHaneleJumpurl"
        >
          <template v-if="dataForm.jumpUrl">
            <span class="select-type"> {{ jumpUrlType[dataForm.jumpUrl.type] }}</span>
            <span class="select">{{ dataForm.jumpUrl.name }}</span>
          </template>
          <span
            v-else
            class="no-select"
          >{{ $t('popupAd.selectRedirect') }}</span>
        </div>
      </el-form-item>
      <el-form-item
        v-if="dataForm.jumpUrl?.type!=='7'"
        :label="$t('popupAd.popupImg')"
        prop="popupPic"
        required
      >
        <img-upload
          v-model="dataForm.popupPic"
          class="upload-box"
          :disabled="readonly"
          @update:model-value="onValidateField('popupPic')"
        />
      </el-form-item>
      <el-form-item
        :label="$t('popupAd.pushUser')"
        prop="userType"
        required
      >
        <!-- 推送用户类型 0.所有用户 1.免费会员 2.付费会员 3.店铺客户 -->
        <el-radio-group
          v-model="dataForm.userType"
          :disabled="readonly"
          @change="onChangeUserType"
        >
          <el-radio :label="0">
            {{ $t('popupAd.allUsers') }}
          </el-radio>
          <el-radio :label="3">
            {{ $t('popupAd.shopCustomer') }}
          </el-radio>
          <el-radio :label="4">
            {{ $t('popupAd.shopMember') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="dataForm.userType===4"
        :label="$t('popupAd.memberLevel')"
        prop="userLevelIds"
        required
      >
        <el-select
          v-model="dataForm.userLevelIds"
          style="width: 355px;"
          :placeholder="$t('popupAd.memberLevel')"
          multiple
          clearable
          :disabled="readonly"
        >
          <el-option
            v-for="level in userLevelList"
            :key="level.id"
            :label="level.levelName"
            :value="level.id"
          />
        </el-select>
      </el-form-item>
      <!--推送时间-->
      <el-form-item
        :label="$t('popupAd.pushTime')"
        :required="true"
      >
        <div class="date-picker">
          <!--开始时间-->
          <el-form-item prop="startTime">
            <el-date-picker
              v-model="dataForm.startTime"
              :disabled="curPageType===2 || popupStatus !==1"
              type="date"
              style="width:140px"
              :placeholder="$t('live.chooseStartDate')"
              value-format="YYYY-MM-DD"
              @change="onChangeDatePicker"
            />
            <el-time-select
              v-model="startTimeValue"
              :class="[startTimeValue ? 'select-time': '']"
              start="00:00"
              step="00:30"
              end="23:30"
              style="width:114px"
              :disabled="curPageType===2 || popupStatus !==1"
              :placeholder="$t('time.startTime')"
              @change="onChangeTime"
            />
          </el-form-item>
          <span style="margin: 0 10px">-</span>
          <!--结束时间-->
          <el-form-item prop="endTime">
            <el-date-picker
              v-model="dataForm.endTime"
              :disabled="readonly"
              type="date"
              style="width:140px"
              :placeholder="$t('live.chooseEndDate')"
              value-format="YYYY-MM-DD"
              @change="onChangeDatePicker"
            />
            <el-time-select
              v-model="endTimeValue"
              :class="[endTimeValue ? 'select-time': '']"
              start="00:00"
              step="00:30"
              end="23:30"
              style="width:114px"
              :disabled="readonly"
              :placeholder="$t('time.endTime')"
              @change="onChangeTime"
            />
          </el-form-item>
        </div>
      </el-form-item>
      <!-- 推送频次 -->
      <el-form-item
        prop="pushFrequency"
        :required="true"
      >
        <template #label>
          <div class="custom-label">
            <span class="label">{{ $t('popupAd.pushFrequency') }}</span>
            <el-tooltip placement="top">
              <template #content>
                {{ $t('popupAd.pushFrequencyTips') }}
              </template>
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        <!-- 推送频次 0.永久一次 1.每次进入 2.自定义频次 -->
        <el-radio-group
          v-model="dataForm.pushFrequency"
          :disabled="readonly"
        >
          <el-radio :label="0">
            {{ $t('popupAd.onceForAll') }}
          </el-radio>
          <el-radio :label="1">
            {{ $t('popupAd.perEntry') }}
          </el-radio>
          <el-radio :label="2">
            {{ $t('popupAd.customFrequency') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 自定义频次 -->
      <el-form-item
        v-if="dataForm.pushFrequency===2"
        :label="$t('popupAd.customFrequency')"
        :required="true"
      >
        <div class="custom-frequency-box">
          <el-radio-group
            v-model="frequencyType"
            :disabled="readonly"
          >
            <el-radio :label="1">
              {{ $t('formData.day') }}
            </el-radio>
            <el-radio :label="2">
              {{ $t('formData.week') }}
            </el-radio>
          </el-radio-group>
          <div
            v-if="frequencyType===1"
            class="day-push frequency"
          >
            <span>{{ $t('popupAd.every') }}</span>
            <el-input
              v-model="dataForm.dayFrequency"
              maxlength="3"
              style="width: 44px;margin: 0 8px;"
              placeholder=""
              :disabled="readonly"
              @blur="onBlurDayFrequency"
              @input="dataForm.dayFrequency = dataForm.dayFrequency.replace(/[^\d]/g,'')"
            />
            <span>{{ $t('formData.day') }}{{ $t('popupAd.pushOnce') }}</span>
          </div>
          <div
            v-if="frequencyType===2"
            class="week-push frequency"
          >
            <span>{{ $t('popupAd.every') }}</span>
            <el-checkbox-group
              v-model="dataForm.weekFrequency"
              class="checkbox-group-box"
              :disabled="readonly"
            >
              <el-checkbox
                v-for="week in weekList"
                :key="week.value"
                :label="week.value"
                :disabled="week.disabled"
              >
                {{ week.label }}
              </el-checkbox>
            </el-checkbox-group>
            <span>{{ $t('popupAd.pushOnce') }}</span>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          @click="onBack"
        >
          {{ $t('common.back') }}
        </el-button>
        <el-button
          v-if="curPageType !== 2 && popupStatus !==3"
          type="primary"
          @click="onSubmit"
        >
          {{ $t('common.confirm') }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 选择跳转路径 -->
    <decorate-dialog-select
      :dialog-visible="jumpUrlDialogVisible"
      :device-type="'mobile'"
      :custom-link-arr="dataForm.jumpUrl"
      :current-select-type="[1, 2, 4, 5, 6, 7]"
      @handle-close="jumpUrlDialogVisible=false"
      @handle-dialog-submit="handleDialogSubmit"
    />
  </div>
</template>

<script setup>
import moment from 'moment'
import { ElMessage } from 'element-plus'
import decorateDialogSelect from '@/components/decorate-dialog-select/index.vue' // 选择商品

const startTimeValue = ref('')
const endTimeValue = ref('')

const dataForm = reactive({
  popupName: '',
  userType: 0, // 推送用户类型 0.所有用户 1.免费会员 2.付费会员 3.店铺客户
  pageType: 4, // 触发页面类型 1.平台首页 2.会员中心 3.支付成功 4.店铺首页 5.商品详情"
  pushFrequency: 0, // 推送频次 0.永久一次 1.每次进入 2.自定义频次
  weekFrequency: []
})

const readonly = computed(() => curPageType.value === 2 || popupStatus.value === 3)

const route = useRoute()
const curPageType = ref(0) // 0新增 1编辑 2查看
const title = ref('')
let popupId = 0
onMounted(() => {
  popupId = route.query.popupId || 0
  curPageType.value = Number(route.query.pageType) || 0
  title.value = [$t('crud.addTitle'), $t('crud.editTitle'), $t('crud.viewBtn')][curPageType.value] + ' ' + $t('popupAd.popupAd')
  useCommonStore().replaceSelectMenu(title.value)
  if (popupId) {
    getDataInfo()
  } else {
    const datetimeRange = getDateTimeRange()
    dataForm.startTime = datetimeRange.startTime
    dataForm.endTime = datetimeRange.endTime
    startTimeValue.value = datetimeRange.currentTime
    endTimeValue.value = datetimeRange.currentTime
    onHandleWeekFrequency()
  }
})

// 获取弹窗信息
const popupStatus = ref(1) // 弹窗状态 1.未开始 2.投放中 3.已结束
const getDataInfo = () => {
  http({
    url: http.adornUrl('/costPerPopup'),
    method: 'get',
    params: {
      popupId
    }
  }).then(({ data }) => {
    data.jumpUrl = JSON.parse(data.jumpUrl)
    // 对分类数据进行处理
    if (data.jumpUrl.type === '2') {
      const { label, value } = data.jumpUrl.link[0]
      data.jumpUrl.link = {
        categoryName: label,
        categoryId: value
      }
    }
    startTimeValue.value = data.startTime ? data.startTime.substring(11, data.startTime.length - 3) : ''
    endTimeValue.value = data.endTime ? data.endTime.substring(11, data.endTime.length - 3) : ''
    data.startTime = data.startTime?.substring(0, 10) || ''
    data.endTime = data.endTime?.substring(0, 10) || ''
    popupStatus.value = data.status
    // 筛选出商品和店铺会员等级
    if (data.popupRelateList) {
      data.userType === 4 && onChangeUserType(data.userType)
      dataForm.userLevelIds = []
      data.popupRelateList.forEach(item => {
        item.userLevelId && dataForm.userLevelIds.push(item.userLevelId)
      })
    } else {
      dataForm.userLevelIds = []
    }
    if (data.weekFrequency) {
      frequencyType.value = 2
      data.weekFrequency = data.weekFrequency.split(',').map(Number)
    } else {
      frequencyType.value = 1
      data.weekFrequency = []
    }
    Object.assign(dataForm, data)
    onHandleProdName() // 处理商品名称回显
    onHandleWeekFrequency()
  })
}

// 处理商品名称回显
const onHandleProdName = () => {
  if (dataForm.jumpUrl.type !== '1') return
  http({
    url: http.adornUrl(`/prod/prod/info/${dataForm.jumpUrl.link}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    dataForm.jumpUrl.name = data.prodName
  })
}

// 处理推送用户类型改变
const userLevelList = ref([])
const onChangeUserType = (userType) => {
  dataForm.userLevelIds = []
  if (userType !== 4) {
    return
  }
  if (!userLevelList.value.length) {
    onGetUserLevel(0)
  }
}
// 获取会员等级列表
const onGetUserLevel = () => {
  http({
    url: http.adornUrl('/user/userLevel/list'),
    method: 'get',
    params: http.adornParams({
      userLevelType: 0
    })
  }).then(({ data }) => {
    userLevelList.value = data
    // 清除掉被删除的会员等级
    for (let i = 0; i < dataForm.userLevelIds.length; i++) {
      const fd = data.find(f => f.id === dataForm.userLevelIds[i])
      if (!fd) {
        dataForm.userLevelIds.splice(i, 1)
        i--
      }
    }
  })
}

// 自定义频率类型
const frequencyType = ref(1) // 1.天 2.周
const weekList = reactive([
  {
    label: $t('time.monday'),
    value: 2,
    disabled: false
  },
  {
    label: $t('time.tuesday'),
    value: 3,
    disabled: false
  },
  {
    label: $t('time.wednesday'),
    value: 4,
    disabled: false
  },
  {
    label: $t('time.thursday'),
    value: 5,
    disabled: false
  },
  {
    label: $t('time.friday'),
    value: 6,
    disabled: false
  },
  {
    label: $t('time.saturday'),
    value: 7,
    disabled: false
  },
  {
    label: $t('time.sunday'),
    value: 1,
    disabled: false
  }
])

// 天频次处理
const onBlurDayFrequency = () => {
  if (dataForm.dayFrequency < 1) {
    dataForm.dayFrequency = 1
  } else if (dataForm.dayFrequency > 31) {
    dataForm.dayFrequency = 31
  }
}

const onChangeDatePicker = () => {
  onChangeTime()
  onHandleWeekFrequency()
}
// 周频次处理
const onHandleWeekFrequency = () => {
  if (!dataForm.startTime || !dataForm.endTime) {
    onHandleWeekList()
    return
  }
  const diffDays = Number(moment(dataForm.endTime).diff(moment(dataForm.startTime), 'days')) + 1
  if (diffDays >= 7) {
    onHandleWeekList()
    return
  }
  const weeks = []
  for (let i = 0; i < diffDays; i++) {
    const week = moment(dataForm.startTime).add(i, 'd').days()
    weeks.push(week === 0 ? 1 : week + 1)
  }
  onHandleWeekList(weeks)
}
const onHandleWeekList = (weeks = [1, 2, 3, 4, 5, 6, 7]) => {
  dataForm.weekFrequency = dataForm.weekFrequency.filter(f => weeks.includes(f))
  weekList.forEach(item => {
    if (weeks.includes(item.value)) {
      item.disabled = false
    } else {
      item.disabled = true
    }
  })
}

// 跳转页面选取
const jumpUrlType = ['',
  $t('pcdecorate.commonModal.goods'),
  $t('pcdecorate.commonModal.category'),
  $t('pcdecorate.commonModal.store'),
  $t('pcdecorate.commonModal.page'),
  $t('pcdecorate.commonModal.smallPage'),
  $t('pcdecorate.commonModal.customLink'),
  $t('user.coupons')]
const jumpUrlDialogVisible = ref(false) // 弹窗显示隐藏
const onHaneleJumpurl = () => {
  if (readonly.value) return
  jumpUrlDialogVisible.value = true
}
const handleDialogSubmit = ({ type, value }) => {
  let obj = {
    name: '',
    link: '',
    type: ''
  }
  switch (Number(type)) {
    case 1: // 商品
      obj = {
        name: value.goodsItem.prodName, // 商品名称
        link: value.goodsItem.prodId, // 商品id
        type: '1'
      }
      break
    case 2: // 分类
      obj = {
        name: value.categoryItem.label, // 分类名字[三级分类的最后的名字]
        link: value.categoryItem.data, // 分类的数据(数组)
        type: '2'
      }
      break
    case 3: // 店铺
      obj = {
        name: value.storeItem.shopName, // 店铺名
        link: value.storeItem.shopId, // 店铺id
        type: '3'
      }
      break
    case 4: // 页面
      obj = {
        name: value.pageItem.title,
        link: value.pageItem.link,
        type: '4'
      }
      break
    case 5: // 微页面
      obj = {
        name: value.smallPageItem.name, // 微页面名
        link: value.smallPageItem.renovationId,
        type: '5'
      }
      break
    case 6: // 自定义链接
      obj = {
        name: value.customLink.url,
        link: value.customLink,
        type: '6'
      }
      break
    case 7: // 优惠券
      obj = {
        name: value.couponsItem.couponName,
        link: value.couponsItem.couponId,
        type: '7'
      }
      break
    default:
      break
  }
  dataForm.jumpUrl = obj
  jumpUrlDialogVisible.value = false
  onValidateField('jumpUrl')
}
// 表单提交
const dataFormRef = ref(null)
const router = useRouter()
let isSubmit = false
const onSubmit = () => {
  if (isSubmit) {
    return
  }
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      dataForm.startTime = dataForm.startTime + ' ' + startTimeValue.value + ':00'
      dataForm.endTime = dataForm.endTime + ' ' + endTimeValue.value + ':00'
      if (dataForm.pushFrequency === 2) {
        if (frequencyType.value === 1 && !dataForm.dayFrequency) {
          return ElMessage({
            message: $t('popupAd.frequencyDayTips'),
            type: 'error',
            duration: 1500
          })
        }
        if (frequencyType.value === 2 && !dataForm.weekFrequency.length) {
          return ElMessage({
            message: $t('popupAd.frequencyWeekTips'),
            type: 'error',
            duration: 1500
          })
        }
      }
      const submitData = JSON.parse(JSON.stringify(dataForm))
      if (frequencyType.value === 1) {
        submitData.dayFrequency = Number(dataForm.dayFrequency)
        submitData.weekFrequency = null
      } else {
        submitData.dayFrequency = null
        submitData.weekFrequency = submitData.weekFrequency?.toString()
      }
      submitData.popupPic = submitData.jumpUrl.type === '7' ? '' : submitData.popupPic
      // 对分类数据进行处理
      if (submitData.jumpUrl.type === '2') {
        const { categoryName, categoryId } = submitData.jumpUrl.link
        submitData.jumpUrl.link = [{ label: categoryName, value: categoryId }]
      }
      submitData.jumpUrl = JSON.stringify(submitData.jumpUrl)
      isSubmit = true
      http({
        url: '/costPerPopup',
        method: dataForm.popupId ? 'put' : 'post',
        data: submitData
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            isSubmit = false
            onBack()
          }
        })
      }).catch(() => {
        isSubmit = false
      })
    }
  })
}

const onChangeTime = () => {
  onValidateField('startTime')
  onValidateField('endTime')
}

const onValidateField = (field) => {
  dataFormRef.value?.validateField(field)
}

const validateTime = (rule, value, callback) => {
  if (rule.field === 'startTime' && (!startTimeValue.value || !dataForm.startTime)) {
    callback(new Error($t('formData.startTimeCannotBeEmpty')))
  }
  if (rule.field === 'endTime' && (!endTimeValue.value || !dataForm.endTime)) {
    callback(new Error($t('formData.endTimeCannotBeEmpty')))
  }
  if (popupStatus.value !== 1 && rule.field === 'startTime') {
    callback()
  }
  const startTime = dataForm.startTime + ' ' + startTimeValue.value + ':00'
  const endTime = dataForm.endTime + ' ' + endTimeValue.value + ':00'
  const seFlag = dataForm.startTime && dataForm.endTime
  if (popupStatus.value !== 1 && rule.field === 'endTime' && new Date() > Date.parse(endTime)) {
    callback(new Error($t('time.tips1')))
  }
  if (rule.field === 'startTime' && new Date() > Date.parse(startTime)) {
    callback(new Error($t('time.tips2')))
  }
  if (rule.field === 'startTime' && seFlag && Date.parse(startTime) >= Date.parse(endTime)) {
    callback(new Error($t('time.tips3')))
  }
  if (rule.field === 'endTime' && seFlag && Date.parse(startTime) >= Date.parse(endTime)) {
    callback(new Error($t('time.tips4')))
  }
  callback()
}

const dataRule = reactive({
  popupName: [
    { required: true, message: $t('popupAd.popupName') + $t('popupAd.noNull'), trigger: 'blur' }
  ],
  popupPic: [
    { required: true, message: $t('popupAd.popupImg') + $t('popupAd.noNull'), trigger: 'blur' }
  ],
  jumpUrl: [
    { required: true, message: $t('popupAd.redirect') + $t('popupAd.noNull'), trigger: 'blur' }
  ],
  userLevelIds: [
    { required: true, message: $t('popupAd.memberLevel') + $t('popupAd.noNull'), trigger: 'change' }
  ],
  startTime: [
    { required: true, message: $t('time.startTime') + $t('popupAd.noNull'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: $t('time.endTime') + $t('popupAd.noNull'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ]
})

const onBack = () => {
  router.replace('/fitment/feature/popup-ad/index')
}

</script>
<style lang="scss" scoped>
@use './add-or-update.scss';
</style>
